package com.wswy.wzcx.ui.user

import android.arch.lifecycle.Observer
import android.os.Bundle
import android.text.TextUtils
import com.che.libcommon.utils.ToastUtils
import com.wswy.wzcx.module.ScTimes
import com.wswy.wzcx.module.base.CBaseFragment
import com.wswy.wzcx.module.validator.ValidatorResult
import com.wswy.wzcx.statistics.BizReport
import com.wswy.wzcx.ui.activity.ITestValidator
import timber.log.Timber

open class BaseVerifyFragment : CBaseFragment(){

    lateinit var loginHolderViewModel: LoginHolderViewModel

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        loginHolderViewModel = provideViewModelFromActivity(LoginHolderViewModel::class.java)
        loginHolderViewModel.getSMSCodeLiveData().observe(this, Observer {
            it?.run {
                if (!isHidden){
                    if (inLoading()){
                        onSending()
                    }else{
                        ScTimes.addSendSms(isOk())
                        if (isOk()){
                            onSendSuccess()
                            //验证码发送成功
                        }else{
                            onSendFail(message)
                        }
                    }

                    loginHolderViewModel.resetSMSCode()

                }


            }


        })


        loginHolderViewModel.getCaptchaLiveData().observe(this, Observer {

            it?.runCatching {

                if (!isHidden && isOk() && data != null){
                    //验证码

                    (activity as? ITestValidator)?.getValidator(data)?.startVerify {ticket ->

                        if (ticket == null){
                            onGVerifyError()
                        }else{
                            onGVerifySuccess(ticket)
                        }
                    }

                }

            }
        })

    }



    open fun onSending(){

    }
    open fun onSendSuccess(){

    }

    open fun onSendFail(msg:String?){
        BizReport.sendException(BizReport.SEND_SMS_ERROR,msg)
    }

    fun startGVerify(){
        loginHolderViewModel.getCaptcha()

//        startVerify {ticket->
//
//            if (ticket == null){
//                onGVerifyError()
//            }else{
//                onGVerifySuccess(ticket)
//            }
//        }
    }

    open fun onGVerifySuccess(ticket:ValidatorResult){

    }
    open fun onGVerifyError(){

        //ToastUtils.showText("验证失败，请返回重试")
    }



    open fun lockLoad(){

    }

    open fun unlockLoad(){

    }

}